package com.woniuxy.qiniuyundemo.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import java.io.*;

/**
 * @Author: linKe
 * @Date: 2021/11/23 15:39
 * @FileName: QiNiuCloudUtil
 * @version: 1.0
 * @Description: 七牛云上传工具类
 */
public class QiniuCloudUtil {

    /**
     * 设置需要操作的账号的AK和SK
     */
    private static final String ACCESS_KEY = "dX7cflQbQtaJ21dWrCOP2N7b-QtjtUEQg9h3xP5N";
    private static final String SECRET_KEY = "JNP9tj_db-uly8G4m2bl34At6A7r8xoaPku-BZvV";
    // 要上传的空间
    private static final String bucketname = "lkq525";

    /**
     * 密钥
      */

    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    /**
     * 图片上传路径
     */
    private static final String DOMAIN = "r24v943u5.hd-bkt.clouddn.com";
    /**
     * 我这里是需要给图片添加水印，所以自定义了图片样式，如果对于上传图片没有格式要求，则可以跳过此步骤。
     */
    //private static final String style = "自定义的图片样式";

    public String getUpToken() {
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
    }

    // 普通上传
    public String upload(String filePath, String fileName) throws IOException {
        // 创建上传对象
        UploadManager uploadManager = new UploadManager();
        try {
            // 调用put方法上传
            String token = auth.uploadToken(bucketname);
            //判断字符串为空的工具类，可用自己的
            if (token==null || "".equals(token)) {
                System.out.println("未获取到token，请重试！");
                return null;
            }
            Response res = uploadManager.put(filePath, fileName, token);
            // 打印返回的信息
            System.out.println(res.bodyString());
            if (res.isOK()) {
                Ret ret = res.jsonToObject(Ret.class);
                //如果不需要对图片进行样式处理，则使用以下方式即可
                return DOMAIN + ret.key;
                //return DOMAIN + ret.key + "?" + style;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                // ignore
            }
        }
        return null;
    }


    //base64方式上传
    public String put64image(byte[] base64, String key) throws Exception {
        String file64 = Base64.encodeToString(base64, 0);
        Integer l = base64.length;
        String url = "http://upload.qiniu.com/putb64/" + l + "/key/" + UrlSafeBase64.encodeToString(key);
        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        //System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
        //如果不需要添加图片样式，使用以下方式
        return DOMAIN +"/"+ key;
        //return DOMAIN + key + "?" + style;
    }


    // 普通删除(暂未使用以下方法，未测试)
    public void delete(String key) throws IOException {
        // 实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth);
        // 此处的6666是去掉：http://你的图片上传路径/,剩下的key就是图片在七牛云的名称
        key = key.substring(6666);
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucketname, key);
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
            System.out.println(r.toString());
        }
    }

    /**
     * 通过发送http get 请求获取文件资源
     * @param url
     * @param filepath
     * @return
     */
    public static String download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        okhttp3.Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                //下载到本地的图片命名
                File imgFile = new File(filepath + "123.png");
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();

                return "200";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "500";
        }
        return "500";
    }
    /**
         * 读取字节输入流内容
         * @param is
         * @return
         */
        public static byte[] readInputStream(InputStream is) {
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            byte[] buff = new byte[1024 * 2];
            int len = 0;
            try {
                while((len = is.read(buff)) != -1) {
                    writer.write(buff, 0, len);
                }
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return writer.toByteArray();
        }


    class Ret {
        public long fsize;
        public String key;
        public String hash;
        public int width;
        public int height;
    }

}
